package com.heima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.pojo.TbUser;
import com.heima.mapper.UserMapper;
import com.heima.pojo.dto.LoginDto;
import com.heima.pojo.vo.LoginUserVo;
import com.heima.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author nan
 * @since 2024-06-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, TbUser> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginUserVo login(LoginDto dto) {
        if(ObjectUtil.isEmpty(dto)){
            throw new  RuntimeException("参数异常");
        }

        LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<TbUser>().eq(TbUser::getLoginName, dto.getLoginName());
        TbUser user = userMapper.selectOne(wrapper);

        if(ObjectUtil.isEmpty(user)){
            throw new RuntimeException("用户不存在");
        }
        LoginUserVo loginUserVo = BeanUtil.toBean(user, LoginUserVo.class);
        loginUserVo.setUserId(user.getId());
        loginUserVo.setSuccess(true);
        loginUserVo.setMsg("登录成功");
        loginUserVo.setToken(UUID.randomUUID().toString());
        return loginUserVo;
    }
}
